package com.maogouxiong.seatatestorder.order.service.impl;

import com.maogouxiong.seatatestorder.order.entity.Order;
import com.maogouxiong.seatatestorder.order.feign.AccountFeignService;
import com.maogouxiong.seatatestorder.order.feign.StorageFeignService;
import com.maogouxiong.seatatestorder.order.mapper.OrderMapper;
import com.maogouxiong.seatatestorder.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author maogouxiong
 * @since 2020-06-19
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountFeignService accountFeignService;

    @Autowired
    private StorageFeignService storageFeignService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void insertOrder(int money, String userId, String commodityCode, int count) {

        log.info("----->开始新建订单");
        //1 新建订单
        Order order = new Order();
        order.setMoney(money);
        order.setCommodityCode(commodityCode);
        order.setCount(count);
        order.setStatus(0);
        order.setUserId(userId);
        orderMapper.insertOrder(order);

        //2 扣减库存
        log.info("----->订单微服务开始调用库存，做扣减Count");
        storageFeignService.reduceStorage(order.getCount(), order.getCommodityCode());
        log.info("----->订单微服务开始调用库存，做扣减end");

        //3 扣减账户
        log.info("----->订单微服务开始调用账户，做扣减Money");
        accountFeignService.reduceBalance(order.getUserId(), order.getMoney());
        log.info("----->订单微服务开始调用账户，做扣减end");

        //4 修改订单状态，从零到1,1代表已经完成
        log.info("----->修改订单状态开始");
        orderMapper.finishOrder();
        //int i=1/0;
        log.info("----->修改订单状态结束");

        log.info("----->下订单结束了，O(∩_∩)O哈哈~");

    }
}
